package com.jmu.edu.IMApplication.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.os.Environment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.GlideException;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.android.material.radiobutton.MaterialRadioButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import com.google.gson.Gson;
import com.jmu.edu.IMApplication.MyApplication;
import com.jmu.edu.IMApplication.R;
import com.jmu.edu.IMApplication.event.LoginEvent;
import com.jmu.edu.IMApplication.net.bean.User;
import com.jmu.edu.IMApplication.utils.HttpUtil;
import com.jmu.edu.IMApplication.utils.ImageTools;
import com.jmu.edu.IMApplication.utils.LoginUtils;
import com.jmu.edu.IMApplication.utils.ViewUtils;
import com.jmu.edu.IMApplication.utils.WillowUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.android.api.options.RegisterOptionalUserInfo;
import cn.jpush.im.api.BasicCallback;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class RegisterFragment extends Fragment {
    private static final String TAG = "register";
    private MaterialButton backButton, reviseAvatarButton, confirmButton;
    private TextInputLayout usernameLayout, passwordLayout, confirmPasswordLayout, nicknameLayout;
    private TextInputEditText usernameText, passwordText, confirmPasswordText, nicknameText;
    private ShapeableImageView avatarImage;
    private MaterialRadioButton maleRadioButton, femaleRadioButton;
    private String avatarFilePath;
    private boolean canRegister = true;

    public RegisterFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_register, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView() {
        backButton = getView().findViewById(R.id.fragment_register_back);
        confirmButton = getView().findViewById(R.id.fragment_register_confirm);
        reviseAvatarButton = getView().findViewById(R.id.fragment_register_revise_avatar);
        avatarImage = getView().findViewById(R.id.fragment_register_avatar);
        usernameLayout = getView().findViewById(R.id.fragment_register_username_layout);
        usernameText = getView().findViewById(R.id.fragment_register_username);
        passwordLayout = getView().findViewById(R.id.fragment_register_password_layout);
        passwordText = getView().findViewById(R.id.fragment_register_password);
        confirmPasswordLayout = getView().findViewById(R.id.fragment_register_confirm_password_layout);
        confirmPasswordText = getView().findViewById(R.id.fragment_register_confirm_password);
        nicknameLayout = getView().findViewById(R.id.fragment_register_nickname_layout);
        nicknameText = getView().findViewById(R.id.fragment_register_nickname);
        maleRadioButton = getView().findViewById(R.id.fragment_register_male);
        femaleRadioButton = getView().findViewById(R.id.fragment_register_female);
        initListener();
    }

    private void initListener() {
        usernameText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() <= 12) {
                    usernameLayout.setErrorEnabled(false);
                } else {
                    usernameLayout.setErrorEnabled(true);
                    usernameLayout.setError("用户名不得超过12位");
                }

            }
        });
        nicknameText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() <= 9) {
                    nicknameLayout.setErrorEnabled(false);
                } else {
                    nicknameLayout.setErrorEnabled(true);
                    nicknameLayout.setError("昵称不得超过9位");
                }
            }
        });
        passwordText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().length() <= 16) {
                    passwordLayout.setErrorEnabled(false);
                } else {
                    passwordLayout.setErrorEnabled(true);
                    passwordLayout.setError("密码不得超过16位");
                }
                if (!confirmPasswordText.getText().toString().isEmpty() && !s.toString().equals(confirmPasswordText.getText().toString())) {

                    confirmPasswordLayout.setErrorEnabled(true);
                    confirmPasswordLayout.setError("两次密码不一致");
                } else {
                    confirmPasswordLayout.setErrorEnabled(false);
                }
            }
        });
        passwordText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    if (passwordText.getText().toString().length() < 8) {
                        passwordLayout.setError("密码不得小于8位");
                        passwordLayout.setErrorEnabled(true);
                    } else {
                        passwordLayout.setErrorEnabled(false);
                    }
                }
            }
        });
        confirmPasswordText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals(passwordText.getText().toString())) {
                    confirmPasswordLayout.setErrorEnabled(false);
                } else {
                    confirmPasswordLayout.setErrorEnabled(true);
                    confirmPasswordLayout.setError("两次密码不一致");
                }

            }
        });
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewUtils.hideFragment(RegisterFragment.this, R.anim.from_right, R.anim.out_right);
            }
        });
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里填写完成注册的代码
                register();
            }
        });
        reviseAvatarButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 这里填写跳转到相册获取选中图片的file的方法
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, 1);
            }
        });
    }

    private void register() {
        //这里还需要检测username是否已被占用
        canRegister = !usernameLayout.isErrorEnabled() && !nicknameLayout.isErrorEnabled() && !passwordLayout.isErrorEnabled() && !confirmPasswordLayout.isErrorEnabled();
        if (canRegister) {

            RegisterOptionalUserInfo registerOptionalUserInfo = new RegisterOptionalUserInfo();
            // 获得注册的基本属性
            String username = usernameText.getText().toString();
            String password = passwordText.getText().toString();
            String nickname = nicknameText.getText().toString();
            // 将属性填充到自己数据库的User和IM框架的User中
            User user = new User();
            user.setUsername(username);

            registerOptionalUserInfo.setNickname(nickname);
            if (maleRadioButton.isChecked()) {
                registerOptionalUserInfo.setGender(UserInfo.Gender.male);
                user.setSex("男");
            } else {
                registerOptionalUserInfo.setGender(UserInfo.Gender.female);
                user.setSex("女");
            }

            LoginUtils.register(username, password, registerOptionalUserInfo, new BasicCallback() {
                @Override
                public void gotResult(int i, String s) {
                    if (i == 0) {
                        Toast.makeText(getContext(), "注册成功", Toast.LENGTH_SHORT).show();
                        File file = getAvatarFile();
                        //移除当前注册用的Fragment，且手动释放内存
                        ViewUtils.removeFragment(RegisterFragment.this);
                        //发送登录事件给LoginFragment
                        EventBus.getDefault().post(new LoginEvent(username, password, file));
                        // 写入自己的数据库
                        registerInServer(user);

                    } else if (i == 871303) {
                        Toast.makeText(getContext(), "该用户已注册!", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getContext(), "注册失败", Toast.LENGTH_SHORT).show();
                    }

                }
            });

        } else {
            Toast.makeText(getContext(), "不满足注册条件，请核对输入的内容", Toast.LENGTH_SHORT).show();
        }
    }

    private void registerInServer(User user) {

        String json = new Gson().toJson(user);
        Log.d(TAG, "registerInServer: json:" + json);
        RequestBody requestBody = RequestBody.create(HttpUtil.JSON, json);
        Request request = new Request.Builder().url(HttpUtil.URL_REGISTER).post(requestBody).build();
        MyApplication.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "onFailure: ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, "onResponse: response:" + response.body().string());
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) {
            return;
        }
        // 1代表跳转到相册
        if (requestCode == 1) {
            //通过uri来获取filePath
            avatarFilePath = ImageTools.getFilePathFromURI(getActivity(), data.getData());
            Glide.with(avatarImage).load(avatarFilePath).into(avatarImage);
        }
    }

    private File getAvatarFile() {
        //如果为空那么就不需要更新了
        if (avatarFilePath == null) {
            return null;
        }
        return new File(avatarFilePath);

    }
}